// pages/setOrgName/setOrgName.js
const app = getApp();
const qiniu = require("../../utils/qiniu.min.js");
var list = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orgName:"",
    nameNum:0,
    multiIndex: [],
    multiArray: [],
    objectMultiArray:[],
    toNext:false,
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  setInput(e){
    this.toggle("detail.orgName", e.detail.value);
    this.toggle("nameNum", e.detail.value.length);
    if (e.detail.value.length >= 2 && e.detail.value.length <= 16 && this.detail.authStatus != 2) {
      this.toggle("disbled", false)
    } else {
      this.toggle("disbled", true)
      this.toggle("title", false)
    }
  },
  setOrgName(e){
    this.toggle("orgName", e.detail.value.trim());
  },
  setName(e){
    this.toggle("name", e.detail.value.trim());
  },
  setIdCode(e) {
    this.toggle("idCode", e.detail.value.trim());
  },
  //机构码
  setCode(e){
    this.toggle("orgCode",e.detail.value.trim())
  },
  btn(){
    var that = this;
    app.req({
      url:"orgmini/org/checkAddOrg",
      method:"post",
      data:{
        "orgName": that.data.detail.orgName,
        "orgId": that.data.detail.id
      },
      success(res){
        if (res.code == 200){
          if (res.data.orgId && res.data.orgId != that.data.orgId){
            that.toggle("title",true)
          }else{
            that.toggle("title", false)
            app.req({
              url:"orgmini/org/updateOrg",
              method:"post",
              data:{
                "id": that.data.detail.id,
                "orgName": that.data.detail.orgName
              },
              success(res){
                if(res.code == 200){
                  var pages = getCurrentPages();
                  var prevPage = pages[pages.length - 2]; // 上一级页面
                  prevPage.setData({
                    ['detail.orgName']: that.data.detail.orgName
                  })
                  wx.navigateBack()
                }
              }
            })
          }
        }
      }
    })
  },
  // 获取组织详情
  detail: function () {
    var that = this;
    app.req({
      // url: "orgmini/org/detail",
      url: "orgmini/org/newGetOrgInfo",
      data: {
        orgId: that.data.orgId
      },
      success: function (res) {
        if (200 == res.code) {
          that.toggle("detail", res.data); 
          console.log("当前组织长度",res.data.orgName.length);
          that.toggle("nameNum", res.data.orgName.length);
          if (that.data.nameNum >= 2 && that.data.nameNum <= 16){
            that.toggle("disbled",false)
          }else{
            that.toggle("disbled", true)
          }
        }
      }
    })
  },
  //提交身份证
  posterimg(e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album','camera'],
      success: function (res) {
        const filepath = res.tempFilePaths[0]
        const src = filepath
        if (type == 3 || type == 4){
          wx.navigateTo({
            url: `/pages/cutFaceHeight/index?src=${src}&type=${type}`,
          })
        }else{
          wx.navigateTo({
            url: `/pages/cutFaceWidth/index?src=${src}&type=${type}`,
          })
        }
      }
    })
  },
  bindMultiPickerChange: function (e) {
    var that = this;
    that.setData({
      "multiIndex[0]": e.detail.value[0],
      "multiIndex[1]": e.detail.value[1]
    })
  },
  bindMultiPickerColumnChange: function (e) {
    console.log(e.detail.value);
    var that = this;
    switch (e.detail.column) {
      case 0:
        list = []
        for (var i in that.data.objectMultiArray) {
          if (that.data.objectMultiArray[i].name == that.data.objectMultiArray[e.detail.value].name) {
            for (var j in that.data.objectMultiArray[i].list){
              list.push(that.data.objectMultiArray[i].list[j].name)
            }
          }
        }
        that.setData({
          "multiArray[1]": list,
          "multiIndex[0]": e.detail.value,
          "multiIndex[1]": 0
        })

    }
  },
  // 保存
  save(){
    var that = this;
    if (!this.data.orgName){
      wx.showToast({
        title: '请输入组织名称',
        icon:"none"
      })
      return
    } else if (that.data.orgName.length < 2){
      wx.showToast({
        title: '请输入正确的组织名称',
        icon: "none"
      })
      return
    }
    if (!this.data.name && this.data.detail.orgType == 3) {
      wx.showToast({
        title: '请输入姓名',
        icon: "none"
      })
      return
    }
    if (!this.data.idCode && this.data.detail.orgType == 3) {
      wx.showToast({
        title: '请输入身份证号',
        icon: "none"
      })
      return
    } else if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(this.data.idCode)) && this.data.detail.orgType == 3){
      wx.showToast({
        title: '请输入正确的身份证号',
        icon: "none"
      })
      return
    }
    if (!this.data.imgCover1 && this.data.detail.orgType == 3) {
      wx.showToast({
        title: '请上传身份证正面材料',
        icon: "none"
      })
      return
    }
    if (!this.data.imgCover2 && this.data.detail.orgType == 3) {
      wx.showToast({
        title: '请上传身份证背面材料',
        icon: "none"
      })
      return
    }
    if (!this.data.orgCode && that.data.detail.orgType != 3) {
      wx.showToast({
        title: '请输入组织机构代码',
        icon: "none"
      })
      return
    } else if (that.data.detail.orgType != 3 && (that.data.orgCode.length < 4 || (/^[\u4e00-\u9fa5]+$/.test(that.data.orgCode)))) {
      wx.showToast({
        title: '请输入正确的组织机构代码',
        icon: "none"
      })
      return
    }
    if (that.data.detail.orgType != 3 && (!that.data.multiArray[0][that.data.multiIndex[0]] || !that.data.multiArray[1][that.data.multiIndex[1]])) {
      wx.showToast({
        title: '请选择省市',
        icon: "none"
      })
      return
    }
    if (!this.data.imgCover3 && this.data.detail.orgType != 3 && that.data.detail.orgType != 3) {
      wx.showToast({
        title: '请上传认证材料',
        icon: "none"
      })
      return
    }
    if (this.data.orgName.length.length < 2 || this.data.orgName.length > 16) {
      this.toggle("disbled", true)
    } else {
      this.toggle("disbled", false)
    }
    app.req({
      url: "orgmini/org/checkAddOrg",
      method: "post",
      data: {
        "orgName": that.data.orgName,
        "orgId": that.data.orgId
      },
      success(res) {
        if (res.code == 200) {
          if (res.data.orgId && res.data.orgId != that.data.orgId) {
            wx.showToast({
              title: '组织名称已存在，请重新输入',
              icon: "none"
            })
            return
          } else if (that.data.detail.orgType != 3){
            that.toggle("toNext", true)
            wx.setNavigationBarTitle({
              title: '上传官方认证申请公函'
            })
          }else{
            that.canNext();
          }
        }
      }
    })
  },
  canNext(){
    if(this.data.lock){
      return
    }
    var that = this;
    if (!that.data.imgCover4 && this.data.detail.orgType != 3) {
      wx.showToast({
        title: '请上传官方认证申请公函',
        icon: "none"
      })
      return
    }
    // 保存名称
    app.req({
      url: "orgmini/org/updateOrg",
      method: "post",
      data: {
        "id": that.data.detail.id,
        "orgName": that.data.orgName
      },
      success(res) {
        if (res.code == 200) {
          var pages = getCurrentPages();
          var prevPage = pages[pages.length - 2]; // 上一级页面
          prevPage.setData({
            ['detail.orgName']: that.data.detail.orgName
          })
        }
      }
    })
    app.req({
      url: "orgmini/org/orgAuthentication",
      method: "post",
      data: {
        "id": that.data.orgId,
        "legalPersonCertificate": that.data.imgCover3,
        "orgCode": that.data.orgCode,
        "legalPersonFile": that.data.imgCover4,
        "orgProvince": that.data.multiArray[0][that.data.multiIndex[0]],
        "orgCity": that.data.multiArray[1][that.data.multiIndex[1]],
        "idcard": that.data.idCode,
        "idcardPositive": that.data.imgCover1,
        "idCardBack": that.data.imgCover2,
        "authenticatedName": that.data.orgName,
        "linkName": that.data.name
      },
      success(res) {
        if (res.code == 200) {
          that.toggle("lock", true)
          wx.showToast({
            title: '申请已提交，请耐心等待',
            icon: 'none',
            duration:3000
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/orgHome/orgHome?id=' + that.data.orgId,
            })
          },2000)
        }
      }
    })
  },
  // 拉取省市列表
  getProvence(){
    var that = this;
    app.req({
      url:"orgmini/org/areaList",
      method:"post",
      data:{
        areaCode:0
      },
      success(res){
        console.log(res)
        var multiArray = [[],[]];
        // var objectMultiArray = [];
        for(var i in res.data){
          multiArray[0].push(res.data[i].name); 
          // objectMultiArray.push({
          //   regid:i,
          //   regname: res.data[i].name
          // })
          for (var j in res.data[i].list){
            multiArray[1].push(res.data[i].list[j].name);
            // objectMultiArray.push({
            //   parid: i,
            //   regname: res.data[i].list[j].name
            // })
          }
        }
        that.toggle("multiArray", multiArray)
        that.toggle("objectMultiArray", res.data)
      }
    })
  },
  downloadUrl(){
    app.req({
      url:"orgmini/officialletter/downloadUrl",
      method:"post",
      success(res){
        if(res.code == 200){
          wx.downloadFile({
            url: res.data,
            success: function (res) {
              const filePath = res.tempFilePath
              wx.openDocument({
                filePath: filePath,
                success: function (res) {
                  console.log('打开文档成功')
                }
              })
            }
          })
        }
      }
    })

    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.toggle("orgId", options.orgId)
    this.detail();
    this.getProvence();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})